// Theme Manager Implementation
class ThemeManager {
    constructor() {
        this.themeToggleBtn = document.getElementById('theme-toggle');
        this.initTheme();
        this.bindEvents();
    }

    initTheme() {
        // 获取保存的主题或系统主题
        const savedTheme = localStorage.getItem('theme');
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        
        if (savedTheme) {
            document.documentElement.setAttribute('data-theme', savedTheme);
        } else if (prefersDark) {
            document.documentElement.setAttribute('data-theme', 'dark');
        }
    }

    bindEvents() {
        this.themeToggleBtn.addEventListener('click', () => this.toggleTheme());
        
        // 监听系统主题变化
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
            if (!localStorage.getItem('theme')) {
                document.documentElement.setAttribute('data-theme', e.matches ? 'dark' : 'light');
            }
        });
    }

    toggleTheme() {
        const currentTheme = document.documentElement.getAttribute('data-theme');
        const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
        
        // 添加过渡类
        document.documentElement.classList.add('theme-transition');
        
        // 设置新主题
        document.documentElement.setAttribute('data-theme', newTheme);
        localStorage.setItem('theme', newTheme);
        
        // 移除过渡类
        setTimeout(() => {
            document.documentElement.classList.remove('theme-transition');
        }, 300);
        
        // 添加切换动画
        this.themeToggleBtn.style.transform = 'scale(0.9)';
        setTimeout(() => {
            this.themeToggleBtn.style.transform = 'scale(1)';
        }, 150);
    }
}

// Initialize Theme Manager
new ThemeManager();

class ImageStitcher {
    constructor() {
        this.maxImages = 8;
        this.images = [];
        this.imageNames = [];
        this.previewArea = document.querySelector('.preview-area');
        this.fileInput = document.getElementById('file-input');
        this.stitchBtn = document.getElementById('stitch-btn');
        this.resultArea = document.querySelector('.result-area');
        
        // 绑定拖拽相关方法
        this.handleDragStart = this.handleDragStart.bind(this);
        this.handleDragOver = this.handleDragOver.bind(this);
        this.handleDrop = this.handleDrop.bind(this);
        this.handleDragEnd = this.handleDragEnd.bind(this);
        
        this.dragSrcElement = null;
        this.initEvents();
    }

    initEvents() {
        this.fileInput.addEventListener('change', (e) => this.handleFileSelect(e));
        this.stitchBtn.addEventListener('click', () => this.stitchImages());
    }

    handleFileSelect(event) {
        const files = Array.from(event.target.files);
        if (files.length + this.images.length > this.maxImages) {
            alert(`最多只能上传${this.maxImages}张图片`);
            return;
        }

        files.forEach(file => {
            if (!file.type.startsWith('image/')) return;
            
            const reader = new FileReader();
            reader.onload = (e) => {
                this.addImageToPreview(e.target.result, file.name);
            };
            reader.readAsDataURL(file);
        });
    }

    addImageToPreview(imageSrc, fileName) {
        const imageItem = document.createElement('div');
        imageItem.className = 'preview-item';
        imageItem.draggable = true;
        
        const img = document.createElement('img');
        img.src = imageSrc;
        
        const nameLabel = document.createElement('div');
        nameLabel.className = 'image-name';
        nameLabel.textContent = fileName;
        
        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'delete-btn';
        deleteBtn.innerHTML = '×';
        deleteBtn.addEventListener('click', () => this.removeImage(imageItem));
        
        imageItem.appendChild(img);
        imageItem.appendChild(nameLabel);
        imageItem.appendChild(deleteBtn);
        this.previewArea.appendChild(imageItem);
        
        this.images.push(imageSrc);
        this.imageNames.push(fileName);
        this.updateStitchButton();
        
        this.addDragListeners(imageItem);
    }

    addDragListeners(item) {
        item.addEventListener('dragstart', this.handleDragStart);
        item.addEventListener('dragover', this.handleDragOver);
        item.addEventListener('drop', this.handleDrop);
        item.addEventListener('dragend', this.handleDragEnd);
    }

    handleDragStart(e) {
        this.dragSrcElement = e.target.closest('.preview-item');
        this.dragSrcElement.classList.add('dragging');
        
        // 设置拖拽时的半透明效果
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/html', ''); // 必须调用setData才能触发拖拽
    }

    handleDragOver(e) {
        e.preventDefault();
        const dragOverItem = e.target.closest('.preview-item');
        
        if (!dragOverItem || dragOverItem === this.dragSrcElement) return;
        
        // 获取所有预览项
        const previewItems = [...this.previewArea.querySelectorAll('.preview-item')];
        const dragOverIndex = previewItems.indexOf(dragOverItem);
        const dragSrcIndex = previewItems.indexOf(this.dragSrcElement);
        
        // 根据拖拽方向决定插入位置
        if (dragOverIndex > dragSrcIndex) {
            dragOverItem.parentNode.insertBefore(this.dragSrcElement, dragOverItem.nextSibling);
        } else {
            dragOverItem.parentNode.insertBefore(this.dragSrcElement, dragOverItem);
        }
        
        // 更新图片数组顺序
        this.updateImagesOrder();
    }

    handleDrop(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    handleDragEnd(e) {
        this.dragSrcElement.classList.remove('dragging');
        this.dragSrcElement = null;
    }

    updateImagesOrder() {
        const items = Array.from(this.previewArea.querySelectorAll('.preview-item'));
        this.images = items.map(item => item.querySelector('img').src);
        this.imageNames = items.map(item => item.querySelector('.image-name').textContent);
    }

    removeImage(imageItem) {
        const index = Array.from(this.previewArea.children).indexOf(imageItem);
        this.images.splice(index, 1);
        this.imageNames.splice(index, 1);
        imageItem.remove();
        this.updateStitchButton();
    }

    updateStitchButton() {
        this.stitchBtn.disabled = this.images.length < 2;
    }

    getDragAfterElement(container, y) {
        const draggableElements = [...container.querySelectorAll('.preview-item:not(.dragging)')];
        
        return draggableElements.reduce((closest, child) => {
            const box = child.getBoundingClientRect();
            const offset = y - box.top - box.height / 2;
            if (offset < 0 && offset > closest.offset) {
                return { offset: offset, element: child };
            } else {
                return closest;
            }
        }, { offset: Number.NEGATIVE_INFINITY }).element;
    }

    drawImageName(ctx, text, x, y, maxWidth) {
        ctx.save();
        
        // 设置文字样式
        ctx.font = '16px -apple-system, BlinkMacSystemFont, sans-serif';
        ctx.fillStyle = 'white';
        ctx.textBaseline = 'top';
        
        // 添加文字背景
        const padding = 5;
        const metrics = ctx.measureText(text);
        const textWidth = Math.min(metrics.width, maxWidth);
        const textHeight = 20;
        
        ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
        ctx.fillRect(x, y, textWidth + padding * 2, textHeight + padding * 2);
        
        // 绘制文字
        ctx.fillStyle = 'white';
        ctx.fillText(text, x + padding, y + padding, maxWidth);
        
        ctx.restore();
    }

    stitchImages() {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        ctx.imageSmoothingEnabled = true;
        ctx.imageSmoothingQuality = 'high';
        
        const maxCanvasWidth = 3840;
        const gap = 5;
        
        let firstRowCount, secondRowCount;
        const totalImages = this.images.length;
        
        if (totalImages <= 4) {
            firstRowCount = totalImages;
            secondRowCount = 0;
        } else if (totalImages === 5) {
            firstRowCount = 3;
            secondRowCount = 2;
        } else if (totalImages === 6) {
            firstRowCount = 3;
            secondRowCount = 3;
        } else if (totalImages === 7) {
            firstRowCount = 4;
            secondRowCount = 3;
        } else {
            firstRowCount = 4;
            secondRowCount = 4;
        }
        
        const loadImages = this.images.map(src => {
            return new Promise((resolve) => {
                const img = new Image();
                img.src = src;
                img.onload = () => {
                    resolve(img);
                };
            });
        });

        Promise.all(loadImages).then(images => {
            let firstRowWidth = 0;
            let firstRowHeight = 0;
            let secondRowWidth = 0;
            let secondRowHeight = 0;
            
            for (let i = 0; i < firstRowCount; i++) {
                firstRowWidth += images[i].width + (i > 0 ? gap : 0);
                firstRowHeight = Math.max(firstRowHeight, images[i].height);
            }
            
            for (let i = 0; i < secondRowCount; i++) {
                const img = images[i + firstRowCount];
                secondRowWidth += img.width + (i > 0 ? gap : 0);
                secondRowHeight = Math.max(secondRowHeight, img.height);
            }
            
            const totalWidth = Math.max(firstRowWidth, secondRowWidth);
            const scale = Math.min(1, maxCanvasWidth / totalWidth);
            
            canvas.width = totalWidth * scale;
            canvas.height = (firstRowHeight + (secondRowHeight > 0 ? secondRowHeight + gap : 0)) * scale;
            
            ctx.fillStyle = '#FFFFFF';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            let x = 0;
            for (let i = 0; i < firstRowCount; i++) {
                const img = images[i];
                const scaledWidth = img.width * scale;
                const scaledHeight = img.height * scale;
                ctx.drawImage(img, x, 0, scaledWidth, scaledHeight);
                
                this.drawImageName(ctx, this.imageNames[i], x + 10, 10, scaledWidth - 20);
                
                x += scaledWidth + gap;
            }
            
            if (secondRowCount > 0) {
                x = 0;
                const y = firstRowHeight * scale + gap;
                for (let i = 0; i < secondRowCount; i++) {
                    const img = images[i + firstRowCount];
                    const scaledWidth = img.width * scale;
                    const scaledHeight = img.height * scale;
                    ctx.drawImage(img, x, y, scaledWidth, scaledHeight);
                    
                    this.drawImageName(ctx, this.imageNames[i + firstRowCount], x + 10, y + 10, scaledWidth - 20);
                    
                    x += scaledWidth + gap;
                }
            }
            
            this.showResult(canvas);
        });
    }

    showResult(canvas) {
        const ctx = canvas.getContext('2d');
        ctx.imageSmoothingEnabled = true;
        ctx.imageSmoothingQuality = 'high';
        
        this.resultArea.innerHTML = '';
        
        const resultImg = document.createElement('img');
        resultImg.src = canvas.toDataURL('image/jpeg', 0.92);
        this.resultArea.appendChild(resultImg);
        
        const downloadBtn = document.createElement('a');
        downloadBtn.href = canvas.toDataURL('image/jpeg', 0.92);
        downloadBtn.download = 'stitched-image.jpg';
        downloadBtn.className = 'upload-button';
        downloadBtn.style.textDecoration = 'none';
        downloadBtn.textContent = '下载拼接结果';
        this.resultArea.appendChild(downloadBtn);
    }
}

// 初始化应用
new ImageStitcher();